﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.Data.Security;
using SiGeSIB.GUI.Properties;

namespace SiGeSIB.GUI.Security
{
	public partial class FManageConnections : Form
	{
		public FManageConnections(ConnectionSchemaCollection connections)
		{
			InitializeComponent();

			_Connections = connections;
			gridConnections.AutoGenerateColumns = false;
			// Permite não colocar imagens na coluna de imagens
			this.gridConnections.Columns["IsDefault"].DefaultCellStyle.NullValue = null;
		}

		private Image DefaultImage = Resources.button_green1;
		private ConnectionSchemaCollection _Connections;
		private DataTable _DtConnections;

		public ConnectionSchema SelectedConnection { get; set; }

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			_LoadData();
		}

		#region Event Handlers
		private void bwLoadData_DoWork(object sender, DoWorkEventArgs e)
		{
			_CreateDataTable();

			if (_Connections != null)
			{
				_DtConnections.BeginLoadData();
				foreach (ConnectionSchema conn in _Connections)
					_DtConnections.Rows.Add(_ConvertToDataRow(conn));
				_DtConnections.EndLoadData();
			}
		}
		private void bwLoadData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if (!IsDisposed)
			{
				if (e.Error == null)
				{
					gridConnections.SuspendLayout();
					gridConnections.DataSource = null;
					gridConnections.DataSource = _DtConnections;
					gridConnections.ResumeLayout();
				}
				else
					throw e.Error;
			}
		}
		private void btnConnect_Click(object sender, EventArgs e)
		{
			_Connect();
		}
		private void tsbAdd_Click(object sender, EventArgs e)
		{
			FEditConnectionContainer frm = new FEditConnectionContainer();
			frm.StartPosition = FormStartPosition.CenterParent;

			if (frm.ShowDialog() == DialogResult.OK)
			{
				ConnectionSchema schema = frm.EditedItem;

				if (schema.Id > 0)
					_LoadData();
			}
		}
		private void tsbEdit_Click(object sender, EventArgs e)
		{
			_EditSelectedSchema();
		}
		private void tsbRemove_Click(object sender, EventArgs e)
		{
			_RemoveSelectedSchema();
		}
		private void ctxDefault_Click(object sender, EventArgs e)
		{
			ConnectionSchema schema = _GetSelectedSchema();
			
			if (schema != null)
			{
				schema.IsDefaultConnection = true;
				ConfigurationManager.Instance.SaveSchema(schema);
				_LoadData();
			}
		} 
		#endregion

		#region Methods
		private void _LoadData()
		{
			bwLoadData.RunWorkerAsync();
		}
		private void _CreateDataTable()
		{
			if (_DtConnections == null)
			{
				_DtConnections = new DataTable();
				_DtConnections.Columns.Add("IsDefault", typeof(Image));
				_DtConnections.Columns.Add("ConnectionName", typeof(string));
				_DtConnections.Columns.Add("Server", typeof(string));
				_DtConnections.Columns.Add("ItemHolder", typeof(ConnectionSchema));
			}
			else
				_DtConnections.Clear();
		}
		private object[] _ConvertToDataRow(ConnectionSchema conn)
		{
			return new object[]
				{
					conn.IsDefaultConnection ? DefaultImage : (object)DBNull.Value,
					conn.ConnectionName,
					conn.DatabaseName,
					conn
				};
		}
		private void _Connect()
		{
			ConnectionSchema schema = _GetSelectedSchema();

			if (schema != null)
			{
				SelectedConnection = schema;
				_Connections.SelectedSchema = schema;
				DialogResult = DialogResult.OK;
				this.Close();
			}
		}
		private void _EditSelectedSchema()
		{
			DataRow dr = _GetSelectedRow();

			if (dr != null)
			{
				ConnectionSchema schema = dr["ItemHolder"] as ConnectionSchema;

				if (schema != null)
				{
					FEditConnectionContainer frm = new FEditConnectionContainer(schema);
					frm.StartPosition = FormStartPosition.CenterParent;

					if (frm.ShowDialog() == DialogResult.OK)
					{
						schema = frm.EditedItem;
						dr.ItemArray = _ConvertToDataRow(schema);
					}
				}
			}
		}
		private void _RemoveSelectedSchema()
		{
			ConnectionSchema schema = _GetSelectedSchema();

			if (schema != null)
			{
				ConfigurationManager.Instance.RemoveSchema(schema.Id);
				_LoadData();
			}
		}
		private DataRow _GetSelectedRow()
		{
			DataRow dr = null;

			DataGridViewRow dvr = gridConnections.SelectedRows != null && gridConnections.SelectedRows.Count > 0 ? gridConnections.SelectedRows[0] : null;

			if (dvr != null && dvr.DataBoundItem != null)
			{
				DataRowView drv = dvr.DataBoundItem as DataRowView;

				if (drv != null)
					dr = drv.Row;
			}

			return dr;
		}
		private ConnectionSchema _GetSelectedSchema()
		{
			ConnectionSchema schema = null;

			DataRow dvr = _GetSelectedRow();

			if (dvr != null)
			{
				schema = dvr["ItemHolder"] as ConnectionSchema;
			}

			return schema;
		} 
		#endregion

		private void gridConnections_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{
			e.Cancel = true;
		}
	}
}
